package com.gitee.easyopen.sdk.util;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;

import com.alibaba.fastjson.JSONObject;

public class PostUtil {

    private static final String UTF8 = "UTF-8";
    private static final String CONTENT_TYPE_JSON = "application/json";
    private static final String ACCEPT_LANGUAGE = "Accept-Language";
    private static final String AUTHORIZATION = "Authorization";
    private static final String PREFIX_BEARER = "Bearer ";

    
    /**
     * POST请求
     * @param url
     * @param params
     * @param lang 语言zh,en
     * @return
     * @throws Exception
     */
    public static String post(String url, JSONObject params, String lang, String jwt) throws Exception {
        String encode = UTF8;
        // 使用 POST 方式提交数据
        PostMethod method = new PostMethod(url);
        try {
            String requestBody = params.toJSONString();
            // 请求数据放在body体中，采用json格式
            method.setRequestEntity(new StringRequestEntity(requestBody, CONTENT_TYPE_JSON, encode));
            // 设置请求语言
            method.setRequestHeader(ACCEPT_LANGUAGE, lang);
            if(jwt != null) {
                method.setRequestHeader(AUTHORIZATION, PREFIX_BEARER + jwt);
            }

            HttpClient client = new HttpClient();
            int state = client.executeMethod(method); // 返回的状态

            if (state != HttpStatus.SC_OK) {
                throw new Exception("HttpStatus is " + state);
            }

            String response = method.getResponseBodyAsString();

            return response; // response就是最后得到的结果
        } catch (Exception e) {
            throw e;
        } finally {
            method.releaseConnection();
        }
    }

}
